[Coding033] LeetCode 25

Reverse Nodes in k-Group

Ben 2024.03.23

More coding records

Get the knowledge flowing and circulating! :)

目录

本题收获

  1. 递归程序写的很巧妙,需要多看看类似的程序,培养自己的递归思维;

  2. 头插法的新写法,用到了prev这个指针,感觉很新奇;

  3. 在解法2中,平铺直叙的叙述下,控制大循环的cnt和内循环的k很值得思考。这个逻辑一开始在写的时候还是比较紊乱的。后来就厘清了!

题目:25. Reverse Nodes in k-Group

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list's nodes, only nodes themselves may be changed.

Example 1:

img

Example 2:

img

Constraints:

Follow-up: Can you solve the problem in O(1) extra memory space?


代码1(配 · 手绘过程图)

image-20240324193033120

Fig. 程序结构

image-20240324192951499

代码解读 | 评价

  • 递归程序,每次处理k个,然后依次把处理好的k个连接起来。

    • 目前对其中的reverseKGroup()这个函数无法特别共鸣,但是可以知道,这个函数每次的headnode.next包裹的内容就是k个待翻转的链表段的(头 和 尾)。

    • 一定要多写写这些程序,才能深刻体会到递归的魅力!

  • 值得借鉴的思想

    • prev这个指针很巧妙,在翻转链表的时候,每次都把新节点放在prev的前面(通过代码p.next = prev;实现),然后再把新的头结点看成prev(通过代码prev = p;实现);

    • 这个比起头插法,显得更简洁明了。(适用于没有dummy的情况)。

复杂度分析

这个挺快的。

image-20240323211050920


代码2(配 · 手绘过程图)

image-20240324193708539

代码解读 | 评价

  • 这段代码相对于上一个用了递归思想的代码,就是平铺直叙的书写方式。

  • 需要特别注意

    • cntk的关系

      • cnt是大循环,k是每次大循环中要翻转的k个元素;

        e.g., 假如说对于7个节点的链表,如果每波翻转3个节点,则要翻转2波;

        即:k = 3, cnt = 2

    • 程序的核心控制就是cntk,但是k每次会更新;

复杂度分析

这个比较慢。

image-20240323211025779